const Password = require('../lib/object/password')
const ApiRes = require('../lib/utils/api-res')
const { userFormat } = require('../services/helper/user')
const UserService = require('../services/user')

// 创建用户
async function createUser(ctx) {
  const userInfo = ctx.state.compiled

  const password = (await Password.hash(userInfo.password)).getValue()

  userInfo.password = password

  const result = await UserService.create(userInfo)
  ctx.body = ApiRes.success(result)
}

// 查询所有用户
async function findAllUser(ctx) {
  const { current, size, username, nickName, phoneNumber, email, status } = ctx.state.compiled

  const result = await UserService.findPage(current, size, null, (original) => {
    let query = original

    if (username) {
      query = query.where('username', 'ilike', `%${username}%`)
    }

    if (nickName) {
      query = query.where('nick_name', 'ilike', `%${nickName}%`)
    }

    if (phoneNumber) {
      query = query.where('phone_number', phoneNumber)
    }

    if (email) {
      query = query.where('email', email)
    }

    if (status) {
      query = query.where('status', status)
    }

    return query
  })

  result.records = result.records.map(userFormat)

  ctx.body = ApiRes.success(result)
}

// 查询单个用户
async function findUserById(ctx) {
  const { id } = ctx.params
  const result = await UserService.findOne(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '用户不存在')
  }
}

// 删除用户
async function deleteUser(ctx) {
  const { id } = ctx.params
  const result = await UserService.remove(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '用户不存在')
  }
}

// 更新用户
async function updateUser(ctx) {
  const { id } = ctx.params
  const userInfo = ctx.state.compiled

  if (userInfo.password) {
    const password = (await Password.hash(userInfo.password)).getValue()
    userInfo.password = password
  }else{
    delete userInfo.password
  }

  const result = await UserService.update(id, userInfo)
  if (result?.length) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '用户不存在')
  }
}

module.exports = {
  createUser,
  findAllUser,
  findUserById,
  deleteUser,
  updateUser
}
